﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Linq;
using CoTime.Model;
using System.Collections.Generic;
using System.Windows.Input;

namespace CoTime.View.UserControls
{
    /// <summary>
    /// Note is like a label
    /// used to group your tasks
    /// </summary>
    public partial class UCNote : UserControl
    {
        #region [ Fields / Properties ]

        private Note Note { get; set; }

        public Int32 Lines { get;private set; }
        public Double InnerWidth { get; set; }

        #endregion

        #region [ Constructors ]

        private UCNote()
        {
            InitializeComponent();
        }

        public UCNote(Note note, Int32 lines, Double width) : this()
        {
            if (note == null)
                throw new ArgumentNullException("note");
            if (String.IsNullOrEmpty(note.Name))
                note.Name = "Task Group " + (note.Id+1);
            this.Note = note;
            this.Lines = lines;
            this.InnerWidth = width;
            InitUIAndData();
        }
        
        #endregion

        #region [ UI Operations ]

        private void InitUIAndData()
        {
            this.UIStackPanel.Width = base.Width;
            for (Int32 i = 0; i < Lines; i++)
            {
                var ucTextBox = new UCTextBox(RandomTextBoxName())
                                    {Width = InnerWidth - 35, FontFamily = new FontFamily("方正舒体")};
                if (i == 0)
                {
                    ucTextBox.Text = this.Note.Name;
                    ucTextBox.Margin = new Thickness(5, 0, 0, 0);
                    ucTextBox.Width = InnerWidth - 5;
                    ucTextBox.FontSize = 24;
                    ucTextBox.FontWeight = FontWeights.DemiBold;
                    ucTextBox.FontStyle = FontStyles.Italic;
                }
                else
                {
                    if (this.Note.Tasks.Count >= i)
                    {
                        var task = this.Note.Tasks[i - 1];
                        ucTextBox.Name = RandomTextBoxName(task.UUID);
                        ucTextBox.Text = task.Title;

                        if (task.Done)
                            ucTextBox.Strikethrough();

                        if (((MainWindow) Application.Current.MainWindow).ucTdt.Contains(task))
                            SetToDoTodayStyle(ucTextBox);
                    }
                }
                this.UIStackPanel.Children.Add(ucTextBox);
            }
        }

        private static void SetToDoTodayStyle(UCTextBox textBox)
        {
            textBox.Foreground = Brushes.Gray;
            textBox.FontStyle = FontStyles.Oblique;
        }

        private static void SetNormalStyle(UCTextBox textBox)
        {
            textBox.Foreground = Brushes.Black;
            textBox.FontStyle = FontStyles.Normal;
            textBox.TextDecorations = null;
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            List<UCTextBox> tasks = this.UIStackPanel.FindAll<UCTextBox>().Skip(1).Where<UCTextBox>(t => !String.IsNullOrWhiteSpace(t.Text) && t.Foreground != Brushes.Gray).ToList<UCTextBox>();
            if (tasks.Count > 0)
            { 
                var selectedTask = tasks.FirstOrDefault<UCTextBox>(t => t.IsFocused);
                if (selectedTask != null)
                {
                    AddToToday(selectedTask);
                }
                else
                {
                    tasks.ForEach(AddToToday);
                }
            }
        }

        #region [ Helpers ]

        private static String RandomTextBoxName()
        {
            return Consts.Title + ModelHelper.GenGuid();
        }

        private static String RandomTextBoxName(String name)
        {
            return Consts.Title + name;
        }

        private void UIGrid_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.T)
            {
                Image_MouseLeftButtonDown(null, null);
            }
        }

        #endregion

        #region [ Bussiness Helper ]

        private static void AddToToday(UCTextBox ucTextBox)
        {
            ((MainWindow) Application.Current.MainWindow).AddTask(new Task(ucTextBox.Name.Replace(Consts.Title, String.Empty))
            {
                Title = ucTextBox.Text
            });
            SetToDoTodayStyle(ucTextBox);
        }

        private UCTextBox GetNoteTaskByUuid(String taskUuid)
        {
            var ucTextBox = this.UIStackPanel.FindAll<UCTextBox>().Skip(1).FirstOrDefault<UCTextBox>(t => !String.IsNullOrWhiteSpace(t.Text) && t.Name.Equals(RandomTextBoxName(taskUuid), StringComparison.OrdinalIgnoreCase));
            return ucTextBox;
        }

        #endregion

        #endregion

        #region [ UI Api ]

        public Note ToNote()
        {
            this.Note.Tasks.Clear();

            var ucTextBoxs = UIStackPanel.FindAll<UCTextBox>();

            for (Int32 i = 0; i < ucTextBoxs.Count; i++)
            { 
                var textBox = ucTextBoxs[i];
                if (i == 0)
                {
                    this.Note.Name = textBox.Text;
                }
                else
                {
                    this.Note.AddTask(new Task()
                    { 
                        UUID = textBox.Name.Replace(Consts.Title,String.Empty),
                        Title = textBox.Text,
                        Done = !String.IsNullOrWhiteSpace(textBox.Text) && textBox.IsStrikethrough()
                    });
                }
            }

            return this.Note;
        }

        public void UpdateTaskDoneStatus(Task task)
        {
            UCTextBox ucTextBox = GetNoteTaskByUuid(task.UUID);
            if (ucTextBox != null)
            {
                if (task.Done)
                    ucTextBox.Strikethrough();
                else
                    ucTextBox.TextDecorations.Clear();
                //
                if(task.LastAct.ActType == ActType.CancelTask)
                {
                    SetNormalStyle(ucTextBox);
                }
            }
        }

        /// <summary>
        /// 清空完成
        /// </summary>
        public void ClearDone()
        {
            List<UCTextBox> ucTextBoxs = this.UIStackPanel.FindAll<UCTextBox>().Skip(1).Where<UCTextBox>(t => t.IsStrikethrough()).ToList<UCTextBox>();
            if (ucTextBoxs.Count > 0)
            {
                ucTextBoxs.ForEach(u => { u.Name = RandomTextBoxName(); 
                                          u.Text = String.Empty;
                                          SetNormalStyle(u);
                });
            }
        }

        #endregion
    }
}
